package com.jdone.compus.controller;

import com.jdone.compus.dto.ApiResponse;
import com.jdone.compus.dto.ImeiRecordDto;
import com.jdone.compus.model.ImeiRecord;
import com.jdone.compus.service.ImeiRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/blow/records")
@Api(value = "IMEI 记录管理", tags = "IMEI 记录管理")
public class ImeiRecordController {

    @Autowired
    private ImeiRecordService service;

    @ApiOperation("新增 IMEI 记录")
    @PostMapping("/end_back/add")
    public ApiResponse add(@RequestBody ImeiRecord dto) {
        return ApiResponse.success(service.create(dto));
    }

    @ApiOperation("根据 ID 查询 IMEI 记录")
    @GetMapping("/end_back/find/{id}")
    public ApiResponse getById(@PathVariable Long id) {
        try {
            return ApiResponse.success(service.getById(id));
        } catch (RuntimeException ex) {
            return ApiResponse.error(ex.getMessage());
        }
    }

    @ApiOperation("分页查询 IMEI 记录（支持按名称和 IMEI 模糊过滤）")
    @GetMapping("/end_back/findAll")
    public ApiResponse list(@Validated ImeiRecordDto dto) {
        Page<ImeiRecord> pageResult = service.listByCriteria(dto);
        return ApiResponse.success(pageResult);
    }

    @ApiOperation("修改 IMEI 记录")
    @PutMapping("/end_back/update/{id}")
    public ApiResponse update(@PathVariable Long id, @RequestBody ImeiRecord dto) {
        try {
            return ApiResponse.success(service.update(id, dto));
        } catch (RuntimeException ex) {
            return ApiResponse.error(ex.getMessage());
        }
    }

    @ApiOperation("删除 IMEI 记录")
    @DeleteMapping("/end_back/delete/{id}")
    public ApiResponse delete(@PathVariable Long id) {
        try {
            return service.logicalDelete(id);
        } catch (RuntimeException ex) {
            return ApiResponse.error(ex.getMessage());
        }
    }

    @ApiOperation("查询所有 IMEI 记录（可按 name 或 imei 模糊过滤）")
    @GetMapping("/records/all")
    public ApiResponse listAll(
            @RequestParam(required = false) String keyword
    ) {
        List<ImeiRecord> list = service.findAll(keyword);
        return ApiResponse.success(list);
    }
}